<?php
/**
 * 用户登陆API
 *
 */
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

class UserController extends BaseController {

	public function index()
	{
		$Mdo = D("Admin/User");
		$ulist = null;
		$wheres = array();

		$user = I('get.user', '', 'trim');
		$role = I('get.role', -1,'intval');
		$sector = I('get.sector', -1, 'intval');
		$status = I('get.status', '-2','intval');
		$sector = I('get.sector', '-1','intval');

		$psize = I('get.psize', $this->$m_psize,'intval');
		if (!$psize)
			$psize = $this->m_psize;
		else if ( $psize > 20 )
			$psize = $this->m_psize;
		$wheres['_string'] = "1=1";
		//超级管理员无法在列表中编辑
		if( 1 != $this->m_user['user_id'])
			$wheres['user.user_id'] = array('neq', 1);

		if ($user) {
			if ( preg_match('#^\d{4,13}$#', $user )) {
                $wheres['user.phone'] = array('like', '%'.$user.'%');
            }
            else {
            	$wherec = array();
            	$wherec['_logic'] = 'OR';
            	$wherec['login_name'] = array('like', '%'.$user.'%');
            	$wherec['nickname'] = array('like', '%'.$user.'%');
            	$wheres['_complex'] = $wherec;
            }
		}

		if (-1 != $sector)
				$wheres['user.sector_id'] = array('eq' , $sector);
		if ( $role != -1)
				$wheres['user.role_id'] = array('eq' , $role);
		if (-2!=$status)
			$wheres['user.state'] = array('eq', $status );
		$cnt = $Mdo->where( $wheres )->count();
		$Page = new \Common\ORG\Page( $cnt, $psize );
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$ulist = $Mdo->field("user.user_id,user.login_name,user.nickname,user.sector_id,user.role_id,user.phone,user.qq,user.weixin,user.email,user.state,user.last_time,role.role_name as rname,sector.sector_name as sname")
		               ->where( $wheres )
					   ->order('user_id desc')
					   ->join('LEFT JOIN role on role.role_id = user.role_id')
					   ->join('LEFT JOIN sector on sector.sector_id=user.sector_id')
					   ->limit($Page->firstRow.','.$Page->listRows )
					   ->select();
		if( $ulist ){
			$res['rcode'] = 1;
			$res['data'] = $ulist;
			$res['pall'] =  $Page->getTotalPages();
			$res['p'] = $Page->nowPage;
			$res['psize'] = $psize;
		}else{
			$res['rcode'] = 2;
			$res['msg'] = "用户记录为空";
		}
		e_json( $res );
	}

	//获取页面操作参数
	public function getPageParam()
	{
		$res = array('rcode'=>1,'sector'=>array(), 'role'=>array(),'msg'=>'');
		$wheres = array();
		$wheres['is_deleted'] = array('neq', 1);
		$MRole = D('Admin/Role');
		$roles = $MRole->field("role_id,role_name,parent_role")->where( $wheres )->select();
		$_roles = array();
        foreach( $roles as $vs ){
            $_roles[$vs['role_id']] = $vs;
        }
        if( 1 == $this->m_user['user_id'])
	       $arr = list_to_tree($roles,'role_id','parent_role', '_child', 0);
       else{
       		$arr = array();
       		$arr[] = $_roles[$this->m_user['role_id']];
		    $arr[0]['_child'] =  list_to_tree($roles,'role_id','parent_role', '_child', $this->m_user['role_id']);
       }
	   $res['role'] = $arr;
	   $MSector = D('Admin/Sector');
	   $secs = $MSector->field("sector_id,info,sector_name,parent_company,parent_sector,manager_id")->where( $wheres )->select();
       $_secs = array();
	   $arr = array();
    	foreach ($secs as $sc ){
            $_secs[$sc['sector_id']] = $sc;
        }
        if (1 == $this->m_user['user_id']) {
            $arr = list_to_tree($secs,'sector_id','parent_sector','_child', 0 );
        }
        else {
            $arr = array();
            $arr[]=$_secs[$this->m_user['sector_id']];
		    $arr[0]['_child'] = list_to_tree($secs,'sector_id','parent_sector','_child', $this->m_user['sector_id']);
        }
	   $res['sector'] = $arr;
		e_json( $res );
	}
	//根据ID获取用户名
	public function getUserInfoById(){
		$User=M("User");
		$glist = null;
		$wheres = array();
		$p_id = I('get.uid', 0,'intval');
		if( $p_id )
		{
			$wheres['user_id'] = array('eq' , $p_id);
			$glist = $User->field('user_id,login_name,nickname,sector_id,role_id,state,phone,qq,weixin,email')->where($wheres)->select();
			echo json_encode( array("puser"=>array_values($glist)));
		}
		exit();
	}

	//密码重置
	public function resetPass()
	{
		$res = array('rcode'=>0,'msg'=>'服务器忙，请稍候再试');
		$MUser=D("User");

		if (IS_POST) {
			$user_id = I('post.user_id', 0,'intval');
			$pwd = I('post.pwd', '','trim');
			$ret = $MUser->resetPass( $user_id, $pwd);

			$res['rcode'] = $ret['r'];
			$res['msg'] = $ret['m'];
		}

		
		e_json( $res );
	}

	//修改部门岗位
	public function changeRoleSector()
	{
		$res = array('rcode'=>0,'msg'=>'服务器忙，请稍候再试');
		$Mdo = D("Admin/User");
		if ( IS_GET ) {
			//
		}
		else {
			$uid = I('post.user_id', 0, 'intval');
			$sector = I('post.sector_id',0, 'intval');
			$role = I('post.role_id', 0, 'intval');
			$fres = $Mdo->changeRoleSector( $uid, $sector, $role );
			$res['rcode'] = $fres['r'];
			$res['msg'] = $fres['m'];
		}

		e_json( $res );
	}
	//添加新用户
	public function addUser() {
		$MUser=D("User");
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		if (IS_GET) {
			//
		}
		else {
			$addData = array();

			$addData['nickname'] =  I('post.nickname', '', 'trim');
			$addData['phone'] =  I('post.phone', '', 'trim');
			$addData['sector_id'] =  I('post.sector_id', 0, 'intval');
			$addData['role_id'] =  I('post.role_id', 0, 'intval');
			$addData['state'] =  I('post.state', 0, 'intval');
			$addData['weixin'] =  I('post.weixin', '', 'trim');
			$addData['qq'] =  I('post.qq', '', 'trim');
			$addData['email'] =  I('post.email', '', 'trim');
			$addData['pwd'] =  I('post.pwd', '', 'trim');
			$addData['email'] =  I('post.email', '', 'trim');
			$addData['teacher_name'] =  I('post.teacher_name', '', 'trim');
			$addData['cert_num'] =  I('post.cert_num', '', 'trim');

			$addres = $MUser->addUser( $addData );
			if( $addres['r'] ){
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
				$res['data'] = $addres['data'];
			} else{
				$res['msg'] = $addres['i'];
			}
		}

		e_json( $res );
	}
	//保存编辑用户信息
	public function saveEdit(){
		$res = array('rcode'=>0,'msg'=>'服务器忙，请稍候再试');
		$MUser=D("Admin/User");
		if (IS_GET) {
			$uid = I('get.user_id',0, 'intval');
			$where = array();
			$where['user_id'] = array('eq', $uid);
			$userInfo = $MUser->where( $where )->find();
			if ($userInfo) {
				if ($userInfo['is_deleted']) {
					$res['msg'] = "";
				}
				else {
					$res['rcode'] =1;
					$res['msg'] = 'OK';
					unset($userInfo['pass']);
					$res['data'] = $userInfo;
				}
			}
			else{
				$res['msg'] = "客户不存在";
			}
		}
		else {
			$uid = I('post.user_id', 0, 'intval');
			$updateData = array();

			$updateData['login_name'] = I('post.login_name','','trim');
			$updateData['nickname'] = I('post.nickname','','trim');
			$updateData['weixin'] = I('post.weixin','','trim');
			$updateData['qq'] = I('post.qq','','trim');
			$updateData['email'] = I('post.email','','trim');
			$updateData['phone'] = I('post.phone','','trim');
			$updateData['cert_num'] = I('post.cert_num','','trim');
			$updateData['state'] = I('post.state', 0,'intval');
			$updateData['teacher_name'] = I('post.teacher_name','','trim');

			$editres = $MUser->updateUserInfo( $uid, $updateData);
			if( $editres['r'] ){
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
				$res['data'] = $editres['d'];
			} else{
				$res['msg'] = $editres['i'];
			}
		}
		e_json( $res );
	}
	//批量删除编辑用户信息
	public function userDelAll(){
		$res = array('rcode'=>0,'msg'=>'服务器忙，请稍候再试');
		$ustr = I('get.ustr','','trim');
		$User=D("User");
		$fres = $User->m_user_del( $ustr );
		$res['rcode'] = $fres['r'];
		$res['msg'] = $fres['m'];
		e_json( $res );
	}

	/**
	 * 根据员工姓名获取员工信息
	 *
	 *@return  array  rcode=>0 没有找到员工
	 *                     =>1 唯一员工
	 *                     =>2 员工重名
	 */
	public function searchByName()
	{
		if( IS_POST ){
			$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
			$name = I('post.name','','trim');
			if( !$name ){
				$res['rcode'] = 0;
				$res['msg'] = "提交参数错误";
			}
			else{
				$MUser = D('Admin/User');
				$wheres = $wherelike = array();
				$wheres['nickname'] = array('eq',$name );
				$userfind = $MUser->field("user_id,nickname,sector_id")->where( $wheres )->find();
				$userlike = FALSE;
				if($name ){
					$wherelike['nickname'] = array('like', $name.'%');
					$userlike = $MUser->field("user_id,nickname,sector_id")
									  ->where( $wherelike )
									  ->select();
				}
				if( $userfind || ( $userlike && 1==count( $userlike ) )  ){ //匹配到一个员工
					$res['data'] = $userfind ? $userfind : $userlike[0];
					$res['rcode'] = 1;
				}
				else if( $userlike && 1<count( $userlike) ){ //匹配到多个员工
					$res['rcode'] = 2;
					$res['msg'] = "匹配到多个结果";
				}
				else{
					$res['rcode'] = 0;
					$res['msg'] = "用户匹配失败";
				}
			}
			e_json( $res );
		}
	}

	/*根据客户姓名获取客户信息*/
	public function searchCustomerName() {
		if( IS_POST ){
			$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
			$name = I('post.name','','trim');
			if( !$name ){
				$res['rcode'] = 0;
				$res['msg'] = "提交参数错误";
			}
			else{
				$MCustomer = D('Admin/Customer');
				$wheres = $wherelike = array();
				$wheres['a.nickname'] = array('eq', $name );
				$userfind = M()->field("a.customer_id,a.nickname,a.phone,b.user_id as sales_id,b.nickname as sales_name,c.user_id as sales_manager,c.nickname as manager_name,d.sector_id as sales_company,d.sector_name as subcompany_name")
								->table('customer as a')
								->join('user as b on b.user_id = a.sales_person')
								->join('user as c on c.user_id = a.sales_manager')
								->join('sector as d on d.sector_id = a.sales_sub_company')
								->where( $wheres )
								->find();
				$userlike = FALSE;
				if( strlen($name)>1 ){
					$wherelike['a.nickname'] = array('like', $name.'%');
					$userlike = M()->field("a.customer_id,a.nickname,a.phone,b.user_id as sales_id,b.nickname as sales_name,c.user_id as sales_manager,c.nickname as manager_name,d.sector_id as sales_company,d.sector_name as subcompany_name")
									->table('customer as a')
									->join('user as b on b.user_id = a.sales_person')
									->join('user as c on c.user_id = a.sales_manager')
									->join('sector as d on d.sector_id = a.sales_sub_company')
									->where( $wherelike )
									->find();

				}
				if( $userfind || ( $userlike && 1==count( $userlike ) )  ){ //匹配到一个客户
					$res['data'] = $userfind ? $userfind : $userlike[0];
					$res['rcode'] = 1;
				}
				else if( $userlike && 1<count( $userlike) ){ //匹配到多个客户
					$res['rcode'] = 2;
					$res['msg'] = "匹配到多个结果";
				}
				else{
					$res['rcode'] = 0;
					$res['msg'] = "用户匹配失败";
				}
			}
			e_json( $res );
		}
	}
}

?>
